/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * ExCoInsertPanel.java
 *
 * Created on 29/11/2011, 23:50:33
 */

package proj5labbd.graphics.exibicaoComercial;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
import proj5labbd.DBInterface;
import proj5labbd.graphics.abstractOpGraphics.OperationPanel;

public class ExCoInsertPanel extends OperationPanel {

    /** Creates new form ExCoInsertPanel */
    public ExCoInsertPanel(ExCoFrame frame, DBInterface dbInterface) {
        super(frame,dbInterface);
        initComponents();
        jbtInsert.addActionListener(new ExCoAction());

    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jpnInsert = new javax.swing.JPanel();
        jlbDate = new javax.swing.JLabel();
        jlbInicio = new javax.swing.JLabel();
        jlbTermino = new javax.swing.JLabel();
        jLabel1 = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jtbCliente = new javax.swing.JTable();
        jftxtIni = new javax.swing.JFormattedTextField();
        jftxtFim = new javax.swing.JFormattedTextField();
        jftxtDate = new javax.swing.JFormattedTextField();
        jLabel2 = new javax.swing.JLabel();
        jScrollPane2 = new javax.swing.JScrollPane();
        jtbProg = new javax.swing.JTable();
        jtxtValor = new javax.swing.JTextField();
        jLabel3 = new javax.swing.JLabel();
        jbtInsert = new javax.swing.JButton();

        setBorder(javax.swing.BorderFactory.createTitledBorder(javax.swing.BorderFactory.createTitledBorder("Insert"), "Inserção"));
        addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                formMouseClicked(evt);
            }
        });
        addComponentListener(new java.awt.event.ComponentAdapter() {
            public void componentShown(java.awt.event.ComponentEvent evt) {
                formComponentShown(evt);
            }
        });

        jpnInsert.setBorder(javax.swing.BorderFactory.createTitledBorder("Parâmetros de inserção"));

        jlbDate.setText("Data de exibição");

        jlbInicio.setText("Horário de início");

        jlbTermino.setText("Horário de término");

        jLabel1.setText("Cliente");

        jtbCliente.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {

            }
        ));
        jtbCliente.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jtbClienteMouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(jtbCliente);

        try {
            jftxtIni.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.MaskFormatter("##:##")));
        } catch (java.text.ParseException ex) {
            ex.printStackTrace();
        }
        jftxtIni.setFocusLostBehavior(javax.swing.JFormattedTextField.COMMIT);

        try {
            jftxtFim.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.MaskFormatter("##:##")));
        } catch (java.text.ParseException ex) {
            ex.printStackTrace();
        }
        jftxtFim.setFocusLostBehavior(javax.swing.JFormattedTextField.COMMIT);

        try {
            jftxtDate.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.MaskFormatter("##-##-####")));
        } catch (java.text.ParseException ex) {
            ex.printStackTrace();
        }
        jftxtDate.setFocusLostBehavior(javax.swing.JFormattedTextField.COMMIT);

        jLabel2.setText("Comercial");

        jtbProg.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {

            }
        ));
        jScrollPane2.setViewportView(jtbProg);

        jLabel3.setText("Preço");

        javax.swing.GroupLayout jpnInsertLayout = new javax.swing.GroupLayout(jpnInsert);
        jpnInsert.setLayout(jpnInsertLayout);
        jpnInsertLayout.setHorizontalGroup(
            jpnInsertLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jpnInsertLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jpnInsertLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jScrollPane2, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 514, Short.MAX_VALUE)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 514, Short.MAX_VALUE)
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, jpnInsertLayout.createSequentialGroup()
                        .addGroup(jpnInsertLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jlbDate)
                            .addComponent(jftxtDate, javax.swing.GroupLayout.PREFERRED_SIZE, 181, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jlbInicio)
                            .addComponent(jftxtIni, javax.swing.GroupLayout.PREFERRED_SIZE, 181, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(18, 18, 18)
                        .addGroup(jpnInsertLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel3)
                            .addGroup(jpnInsertLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                .addComponent(jtxtValor)
                                .addComponent(jlbTermino)
                                .addComponent(jftxtFim, javax.swing.GroupLayout.DEFAULT_SIZE, 181, Short.MAX_VALUE))))
                    .addComponent(jLabel1, javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel2, javax.swing.GroupLayout.Alignment.LEADING))
                .addContainerGap())
        );
        jpnInsertLayout.setVerticalGroup(
            jpnInsertLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jpnInsertLayout.createSequentialGroup()
                .addGroup(jpnInsertLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jlbDate)
                    .addComponent(jLabel3))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jpnInsertLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jftxtDate, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jtxtValor, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jpnInsertLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jpnInsertLayout.createSequentialGroup()
                        .addComponent(jlbTermino)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jftxtFim, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(jpnInsertLayout.createSequentialGroup()
                        .addComponent(jlbInicio)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jftxtIni, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addGap(12, 12, 12)
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 101, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel2)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 95, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        jbtInsert.setText("Inserir");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jpnInsert, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addGap(12, 12, 12))
                    .addComponent(jbtInsert, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 90, javax.swing.GroupLayout.PREFERRED_SIZE)))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jpnInsert, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 9, Short.MAX_VALUE)
                .addComponent(jbtInsert))
        );
    }// </editor-fold>//GEN-END:initComponents
    
    /*
     * Resgata as informações das tabelas que serão exibidas
     */
    private void formComponentShown(java.awt.event.ComponentEvent evt) {//GEN-FIRST:event_formComponentShown
        try {
            // TODO add your handling code here:
            setupTables();
        } catch (SQLException ex) {
            JOptionPane.showMessageDialog(null, "Não foi possível resgatar as informações das tabelas");
            frame.printException(ex);
        }
    }//GEN-LAST:event_formComponentShown

    private void jtbClienteMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jtbClienteMouseClicked
      
    }//GEN-LAST:event_jtbClienteMouseClicked

    /*
     * Trata eventos do mouse
     */
    private void formMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_formMouseClicked
        // TODO add your handling code here:
        jtbCliente.clearSelection();
        jtbProg.clearSelection();
    }//GEN-LAST:event_formMouseClicked


    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JButton jbtInsert;
    private javax.swing.JFormattedTextField jftxtDate;
    private javax.swing.JFormattedTextField jftxtFim;
    private javax.swing.JFormattedTextField jftxtIni;
    private javax.swing.JLabel jlbDate;
    private javax.swing.JLabel jlbInicio;
    private javax.swing.JLabel jlbTermino;
    private javax.swing.JPanel jpnInsert;
    private javax.swing.JTable jtbCliente;
    private javax.swing.JTable jtbProg;
    private javax.swing.JTextField jtxtValor;
    // End of variables declaration//GEN-END:variables

    /*
     * Formata as tabelas cliente e comercial para serem exibidas
     */
    private void setupTables() throws SQLException {
        String[] title1 = {"CNPJ", "Nome completo", "Nome fantasia"};
        String[] field1 = {"cnpjCl", "nomeCompletoCl", "nomeFantasiaCl"};
        String[] table1 = {"cliente"};
        DefaultTableModel model = new DefaultTableModel(dbInterface.view(field1, null, table1), title1);
        jtbCliente.setModel(model);
        jtbCliente.setRowSelectionAllowed(true);
        String[] title2 = {"ID", "Título"};
        String[] field2 = {"idPr", "tituloPr"};
        String[] table2 = {"comercial"};
        model = new DefaultTableModel(dbInterface.view(field2, null, table2), title2);
        jtbProg.setModel(model);
        jtbProg.setRowSelectionAllowed(true);
    }

    class ExCoAction implements ActionListener {

        /*
         * Controla os eventos de inserção
         */
        public void actionPerformed(ActionEvent e) {
            if ( jtbCliente.getSelectedRowCount() == 1 && jftxtDate.getText() != "  -  -    "
                        && jftxtIni.getText() != "  :  " && 
                    jtxtValor.getText().trim().compareTo("") != 0 &&
                    jtbProg.getSelectedRowCount() == 1) {
                    ArrayList<String> params = new ArrayList<String>();
                    ArrayList<String> fields = new ArrayList<String>();

                    params.add((String)jtbProg.getValueAt(jtbProg.getSelectedRow(), 0));
                    fields.add("idPr");
                    params.add("TO_DATE('"+jftxtDate.getText()+"','DD-MM-YYYY')");
                    fields.add("dataExCo");

                    params.add("'"+jftxtIni.getText()+"'");
                    fields.add("horaInicioExCo");

                    if (jftxtFim.getText() != "") {
                        params.add("'"+jftxtFim.getText()+"'");
                        fields.add("horaFimExCo");
                    }
                    
                    params.add(jtxtValor.getText());
                    fields.add("precoExCo");

                    params.add("'"+(String)jtbCliente.getValueAt(jtbCliente.getSelectedRow(), 0)+"'");
                    fields.add("cnpjCl");

                    String [] paramArray = new String[params.size()];
                    String [] fieldArray = new String[fields.size()];

                    params.toArray(paramArray);
                    fields.toArray(fieldArray);
                    try {
                        dbInterface.insert(fieldArray, paramArray, new String[]{"exibicaoComercial"});
                    } catch (SQLException ex) {
                        frame.printException(ex);
                        JOptionPane.showMessageDialog(null, "Erro ao tentar inserir a tupla.");
                    }

                }
                else if (jtbCliente.getSelectedRowCount() != 1 && jtbProg.getSelectedRow() != 1) {
                    JOptionPane.showMessageDialog(null, "Você deve escolher um cliente e o programa referente à exibição.");
                }
                else if (jftxtDate.getText() == "  -  -    ") {
                    JOptionPane.showMessageDialog(null, "Você deve inserir uma data da exibição.");
                }
                else if (jftxtIni.getText() == "  :  ") {
                    JOptionPane.showMessageDialog(null, "Você deve inserir um horário de inicio da exibição.");
                }
        }

    }
}
